/**   
 *    
 * 项目名称：SmartKungFuService   
 * 类名称：SendSmsServlet   
 * 类描述：   短信接口
 * 创建人：zhangl  
 * 创建时间：2016年10月25日 下午4:50:10   
 * 修改人：zhangl   
 * 修改时间：2016年10月25日 下午4:50:10   
 * 修改备注：   
 * @version    
 *    
 */
package com.lst.servlet;

import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.StringUtils;

import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.lst.base.entity.BaseRequest;
import com.lst.base.entity.BaseResponse;
import com.lst.common.CommCode;
import com.lst.common.CommFun;
import com.lst.dao.MstClientMapper;
import com.lst.dao.MstMessageMapper;
import com.lst.entity.request.SmsReqPara;
import com.lst.entity.response.SmsResPara;
import com.lst.model.MstClient;
import com.lst.model.MstMessage;
import com.lst.utils.CommonUtils;
import com.lst.utils.DateUtil;
import com.lst.utils.RequestUtils;

/**
 * @ClassName: SendSmsServlet
 * @Description: 短信接口
 * @author zhangl
 * @date 2016年10月25日 下午4:50:10
 *
 */
public class SendSmsServlet extends BaseServlet {

	private static final long serialVersionUID = 1L;

	private MstMessageMapper mstMessageMapper = ctx.getBean(MstMessageMapper.class);

	private MstClientMapper mstClientMapper = ctx.getBean(MstClientMapper.class);
	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) {
		doPost(request, response);
	}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) {
		Date startDate = new Date();
		logger.info("doPost begin: " + startDate);

		SmsResPara smsResPara = new SmsResPara();

		try {
			SmsReqPara smsReqPara = getReqPara(request);

			if(isCheckField(smsReqPara,smsResPara)){
				String userid = smsReqPara.getUserid();
				String mobileno = smsReqPara.getMobileno();
				String receivetype = smsReqPara.getReceivetype();
				String mirror = smsReqPara.getMirror();
				String content = getContent(mirror);
				String values = smsReqPara.getValues();
				String verCode = "";
				String title = "";

				if(!StringUtils.isEmpty(content)){

					//获取验证码
					if("captcha".equals(mirror) || "resetpwd".equals(mirror)|| "bindmobile".equals(mirror)){
						verCode = CommFun.getVerCodeWith6Bit();
						title = "短信验证码" ;
						content = content.replace("${V1}", verCode);
					} 
					
					//客户端接收退款通知结果
					if("refund".equals(mirror)){
						String [] valueArr = values.split("\\|");
						
						if(valueArr == null || valueArr.length != 2){
							content = null;
						} else {
							content = content.replace("${V1}", valueArr[0]).replace("${V2}", valueArr[1]);
						}
						
					}
					
					//客户下订单通知
					if("payment".equals(mirror)){
						String [] valueArr = values.split("\\|");
						
						if(valueArr == null || valueArr.length != 3){
							content = null;
						} else {
							content = content.replace("${V1}", valueArr[0]).replace("${V2}", valueArr[1]).replace("${V3}", valueArr[2]);
						}
					}
					
					String result = CommFun.sendSMSInland(mobileno, content.replace(" ", "").replace(" ", ""));
                
					//短信对象
					MstMessage mstMessage = new MstMessage();
					mstMessage.setContent(content);
					mstMessage.setCreatedate(startDate);
					mstMessage.setCreateuser(Integer.valueOf(userid));
					mstMessage.setEnabled(true);
					mstMessage.setIsdeleted(false);
					mstMessage.setReceiveid(Integer.valueOf(userid));
					mstMessage.setReceivetype(Integer.valueOf(receivetype));
					mstMessage.setSendid(-1);
					mstMessage.setSendtype(CommCode.SYSCODE_MSG_TYPE_SEND_SYSTEM);
					mstMessage.setTitle(title);
					mstMessage.setType(CommCode.SYSCODE_MSG_TYPE_MSG);
					mstMessage.setReserved9(result);//通道公司返回结果
					mstMessage.setReserved10(mobileno);
			//		mstMessage.setReserved11(verCode);

					mstMessageMapper.insert(mstMessage);

					if("0".equals(result)){
						smsResPara.setCaptcha(verCode);
						smsResPara.setCode(CommCode.M_Y000000);
						smsResPara.setMessage(CommCode.M_Y000001);
					} else {
						smsResPara.setCode(CommCode.M_A000000);
						smsResPara.setMessage("发送频繁，请重试");
					}
				}else{
					smsResPara.setCode(CommCode.M_A000000);
					smsResPara.setMessage(CommCode.M_O000008);
				}
			}

		} catch (Exception e) {
			smsResPara.setCode(CommCode.M_A000000);
			smsResPara.setMessage(CommCode.M_SYS0001);

			logger.error("doPost error: ", e);
		}

		try {
			response.setContentType("application/json;charset=utf-8");
			response.setHeader("pragma", "no-cache");
			response.setHeader("cache-control", "no-cache");

			Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").excludeFieldsWithoutExposeAnnotation().create();
			String jsonResult = gson.toJson(smsResPara);
			logger.info(jsonResult);

			PrintWriter out = response.getWriter();
			out.print(jsonResult);
			out.flush();
			out.close();

			logger.info("doPost end run(s): " + DateUtil.calLastedTime(startDate));
		} catch (Exception e) {
			smsResPara.setCode(CommCode.M_A000000);
			smsResPara.setMessage(CommCode.M_SYS0003);

			logger.error("doPost error: ", e);
		}
	}

	@Override
	public boolean isCheckField(BaseRequest reqPara, BaseResponse resPara) {
		boolean flag = false;

		SmsReqPara smsReqPara = (SmsReqPara) reqPara;
		SmsResPara smsResPara = (SmsResPara) resPara;

		if(StringUtils.isEmpty(smsReqPara.getUserid())){
			smsResPara.setCode(CommCode.M_A000000);
			smsResPara.setMessage(CommCode.M_P000002);
		} else if(StringUtils.isEmpty(smsReqPara.getMobileno())){
			smsResPara.setCode(CommCode.M_A000000);
			smsResPara.setMessage(CommCode.M_P000004);
		} else if(StringUtils.isEmpty(smsReqPara.getReceivetype())){
			smsResPara.setCode(CommCode.M_A000000);
			smsResPara.setMessage(CommCode.M_O000007);
		} else if(StringUtils.isEmpty(smsReqPara.getMirror())){
			smsResPara.setCode(CommCode.M_A000000);
			smsResPara.setMessage(CommCode.M_O000009);
		} else{
			//拦截同一手机号一天且能发送5次短信，并验证手机号唯一
			
			if("captcha".equals(smsReqPara.getMirror()) || "resetpwd".equals(smsReqPara.getMirror())|| "bindmobile".equals(smsReqPara.getMirror())){
				Map<String, Object> reqMap = new HashMap<String, Object>();
				reqMap.put("enabled", true);
				reqMap.put("isDeleted", false);
				reqMap.put("reserved9", "0");
				reqMap.put("reserved10", smsReqPara.getMobileno());
				reqMap.put("title", "短信验证码");
				
				String nowDate = DateUtil.date2Str(new Date(), DateUtil.ALL_DATE_HORIZONTAL);
				String startTime = nowDate + CommCode.START_DATE_HMS;
				String endTime = nowDate + CommCode.END_DATE_HMS;
				
				reqMap.put("startTime",startTime);
				reqMap.put("endTime",endTime);
				
				PageBounds pageBounds = new PageBounds();
				
				List<MstMessage> list = mstMessageMapper.queryByList(reqMap, pageBounds);
				
				
				if(list.size() > 5){
					smsResPara.setCode(CommCode.M_A000000);
					smsResPara.setMessage(CommCode.M_O000011);
				}else{
					Map<String, Object> cliMap = new HashMap<String, Object>();
					cliMap.put("enabled", true);
					cliMap.put("isDeleted", false);
					cliMap.put("mobileno",  smsReqPara.getMobileno());
					
					List<MstClient> mstClient = mstClientMapper.queryByList(cliMap, pageBounds);
					if("captcha".equals(smsReqPara.getMirror()) && !mstClient.isEmpty()){
						smsResPara.setCode(CommCode.M_A000000);
						smsResPara.setMessage(CommCode.M_O000012);
						
						return flag;
					}
					
					if("resetpwd".equals(smsReqPara.getMirror()) && mstClient.isEmpty()){
						smsResPara.setCode(CommCode.M_A000000);
						smsResPara.setMessage(CommCode.M_O000013);
						
						return flag;
					}
					
					flag = true;
					
					return flag;
					
				}
			}else{
				flag = true;
			}
		}

		return  flag;
	}

	@Override
	public SmsReqPara getReqPara(HttpServletRequest request) {
		SmsReqPara smsReqPara = null;

		try {
			BaseRequest baseRequest = RequestUtils.getRequestPara(request, new SmsReqPara());
			smsReqPara = (SmsReqPara) baseRequest.clone();

			String userid = request.getParameter("userid");
			String mobileno = request.getParameter("mobileno");
			String receivetype = request.getParameter("receivetype");
			String mirror = request.getParameter("mirror");
			String values = request.getParameter("values");

			logger.info("reqPara userid: " + userid);
			logger.info("reqPara mobileno: " + mobileno);
			logger.info("reqPara receivetype: " + receivetype);
			logger.info("reqPara mirror: " + mirror);
			logger.info("reqPara values: " + values);

			smsReqPara.setUserid(userid);
			smsReqPara.setMobileno(mobileno);
			smsReqPara.setReceivetype(receivetype);
			smsReqPara.setMirror(mirror);
			smsReqPara.setValues(values);
			
		} catch (Exception e) {
			logger.error("getReqPara error: ", e);
		}

		return smsReqPara;
	}

	/**
	 * 
	 * @Title: getContent
	 * @Description:获取模板内容
	 * @param @param mirror
	 * @param @return
	 * @param @throws Exception    设定文件
	 * @return String    返回类型
	 */
	private String getContent(String mirror) throws Exception{
		String _mirror = mirror.toLowerCase();
		
		String methodName = "getSms_model_" + _mirror;

		Class<CommonUtils> cls = CommonUtils.class;
		Method method = cls.getDeclaredMethod(methodName);

		Object obj = method.invoke(cls);

		if(obj != null){
			return obj.toString();
		}else{
			return null;
		}
	}
	
}
